package aole.codeflow.util;

import java.io.File;
import java.io.IOException;

import javafx.collections.ObservableList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import aole.codeflow.Code;

public class XML {

	public static void load( ObservableList<Code> data, File fXmlFile ) throws ParserConfigurationException,
			SAXException, IOException {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse( fXmlFile );
		doc.getDocumentElement().normalize();

		NodeList nList = doc.getElementsByTagName( "table" );
		Node row = nList.item( 0 );

		for( Node c = row.getFirstChild(); c != null; c = c
				.getNextSibling() ) {
			if( c.getNodeType() == Node.ELEMENT_NODE ) {
				Element ce = (Element)c;
				int sr = Integer.parseInt( ce.getAttribute( "serial" ));
				String code = ce.getAttribute( "code" );
				
				Code nc = new Code(sr, code);
				data.add( nc );
			}
		}
	}

	public static void save( ObservableList<Code> data, File fXmlFile ) throws ParserConfigurationException,
			TransformerException {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement( "table" );

		for( Code c: data ) {
			// class elements
			Element ce = doc.createElement( "row" );
			rootElement.appendChild( ce );
			ce.setAttribute( "serial", c.getSerial()+"" );
			ce.setAttribute( "code", c.getCode() );
		}
		doc.appendChild( rootElement );

		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource( doc );
		StreamResult result = new StreamResult( fXmlFile );
		transformer.transform( source, result );
	}

}
